import React, { useState, useEffect, useRef } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import axios from 'axios';
import SockJS from 'sockjs-client';
import { Client } from '@stomp/stompjs';

const DocumentEditor = ({ user }) => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [document, setDocument] = useState(null);
  const [content, setContent] = useState('');
  const [loading, setLoading] = useState(true);
  const [connected, setConnected] = useState(false);
  // const [onlineUsers, setOnlineUsers] = useState([]);
  const stompClientRef = useRef(null);

  useEffect(() => {
    loadDocument();
    connectWebSocket();

    return () => {
      if (stompClientRef.current) {
        stompClientRef.current.deactivate();
      }
      if (saveTimeoutRef.current) {
        clearTimeout(saveTimeoutRef.current);
      }
    };
  }, [id, user]);

  const loadDocument = async () => {
    try {
      const response = await axios.get(`/api/documents/${id}`);
      setDocument(response.data);
      setContent(response.data.content || '');
    } catch (error) {
      console.error('加载文档失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const connectWebSocket = () => {
    const protocol = window.location.protocol === 'https:' ? 'https:' : 'http:';
    const wsUrl = `${protocol}//${window.location.host}/ws`;
    
    const client = new Client({
      webSocketFactory: () => new SockJS(wsUrl),
      debug: (str) => console.log(str),
      onConnect: () => {
        setConnected(true);
        stompClientRef.current = client;

        // 订阅实时编辑消息（不保存到数据库）
        client.subscribe(`/topic/document/${id}`, (message) => {
          const msg = JSON.parse(message.body);
          if (msg.userId !== user.id) {
            setContent(msg.content);
          }
        });

        // 订阅保存确认消息
        client.subscribe(`/topic/document/${id}/saved`, (message) => {
          const msg = JSON.parse(message.body);
          console.log('文档已保存到数据库:', msg.timestamp);
        });

        // 发送加入消息
        client.publish({
          destination: `/app/document/${id}/cursor`,
          body: JSON.stringify({
            documentId: parseInt(id),
            userId: user.id,
            username: user.username,
            type: 'JOIN',
            timestamp: new Date().toISOString()
          })
        });
      },
      onDisconnect: () => {
        setConnected(false);
      }
    });
    
    client.activate();
  };

  // 防抖保存的引用
  const saveTimeoutRef = useRef(null);
  
  const handleContentChange = (newContent) => {
    setContent(newContent);

    // 1. 立即通过WebSocket广播给其他用户（不保存到数据库）
    if (stompClientRef.current && stompClientRef.current.connected) {
      stompClientRef.current.publish({
        destination: `/app/document/${id}/edit`,
        body: JSON.stringify({
          documentId: parseInt(id),
          userId: user.id,
          username: user.username,
          content: newContent,
          type: 'EDIT',
          timestamp: new Date().toISOString()
        })
      });
    }

    // 2. 防抖自动保存（用户停止输入2秒后保存）
    if (saveTimeoutRef.current) {
      clearTimeout(saveTimeoutRef.current);
    }
    
    saveTimeoutRef.current = setTimeout(() => {
      if (stompClientRef.current && stompClientRef.current.connected) {
        stompClientRef.current.publish({
          destination: `/app/document/${id}/save`,
          body: JSON.stringify({
            documentId: parseInt(id),
            userId: user.id,
            username: user.username,
            content: newContent,
            type: 'AUTO_SAVE',
            timestamp: new Date().toISOString()
          })
        });
      }
    }, 2000); // 2秒防抖
  };

  const saveDocument = async () => {
    try {
      if (stompClientRef.current && stompClientRef.current.connected) {
        // 通过WebSocket立即保存
        stompClientRef.current.publish({
          destination: `/app/document/${id}/save`,
          body: JSON.stringify({
            documentId: parseInt(id),
            userId: user.id,
            username: user.username,
            content: content,
            type: 'SAVE',
            timestamp: new Date().toISOString()
          })
        });
        alert('文档已保存到数据库');
      } else {
        // WebSocket不可用时的备用方案
        await axios.put(`/api/documents/${id}`, {
          ...document,
          content: content
        });
        alert('文档已保存');
      }
    } catch (error) {
      console.error('保存文档失败:', error);
      alert('保存失败');
    }
  };

  if (loading) {
    return <div className="container">加载中...</div>;
  }

  if (!document) {
    return <div className="container">文档不存在</div>;
  }

  return (
    <div className="container">
      <div className="editor-container">
        <div className="editor-header">
          <div>
            <h2>{document.title}</h2>
            <p>
              状态: {connected ? '已连接' : '连接中...'}
              <span style={{ marginLeft: '20px' }}>
                最后修改: {new Date(document.updatedAt).toLocaleString()}
              </span>
            </p>
          </div>
          <div>
            <button className="btn btn-primary" onClick={saveDocument}>
              保存
            </button>
            <button 
              className="btn btn-secondary" 
              onClick={() => navigate('/dashboard')}
              style={{ marginLeft: '10px' }}
            >
              返回
            </button>
          </div>
        </div>

        <div style={{ display: 'flex', gap: '20px' }}>
          <div style={{ flex: 1 }}>
            <textarea
              className="editor-textarea"
              value={content}
              onChange={(e) => handleContentChange(e.target.value)}
              placeholder="开始编辑文档..."
            />
          </div>
          
          <div style={{ width: '200px' }}>
            <div className="card">
              <h4>在线用户</h4>
              <div className="user-list">
                <div className="user-item">
                  <div className="user-avatar">
                    {user.username.charAt(0).toUpperCase()}
                  </div>
                  <span>{user.username} (你)</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default DocumentEditor;